package nus.mtech.presistence.oflite;


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
 * Object file persistence object
 * used to write value object lists to file
 * 
 * @author Guo Yu
 */

public class OFWriter{
	private String fileName;
	private String delimiter;
	private Class targetClass;
	private BufferedWriter bw;
	private List<Method> methodList;

	public OFWriter(Class targetClass, String fileName) throws IOException{
		this(targetClass, fileName, ",");
	}

	public OFWriter(Class targetClass, String fileName, String delimiter) throws IOException{
		this.targetClass = targetClass;
		this.fileName = fileName;
		this.delimiter = delimiter;
		init();
	}
	
	private void init() throws IOException {
		bw = new BufferedWriter(new FileWriter(fileName));
		methodList = new ArrayList<Method>();
		Method [] methods = targetClass.getMethods();
		for(Method m:methods){
			if(m.getName().startsWith("get")||m.getName().startsWith("is")){
				if("getClass".equals(m.getName()))
					continue;
				methodList.add(m);
			}
		}
	}
	/**
	 * write list object into file.
	 * first line is header. header format: 
	 * value object get and set method name (omit "set" and "get")
	 * refer a.txt for example
	 * 
	 * @param objList
	 * @throws IOException
	 */
	public void saveAll(List objList) throws IOException {
		StringBuilder sb = new StringBuilder();
		for(int i = 0 ; i < methodList.size(); i++){
			if (i != 0)
				sb.append(delimiter);
			String methodName = methodList.get(i).getName();
			int startPoint = 3;
			if(methodName.startsWith("is"))
				startPoint = 2;
			sb.append(methodList.get(i).getName().substring(startPoint));
		}
		sb.append("\n");
		bw.write(sb.toString());
		for(int i = 0; i < objList.size(); i++){
			sb = new StringBuilder();
			for(int j = 0; j < methodList.size(); j++){
				if(j != 0)
					sb.append(delimiter);
				try{
					Object returnValue =  methodList.get(j).invoke(objList.get(i));
					sb.append(String.valueOf(returnValue));
				}
				catch(Exception e){
					e.printStackTrace();
				}
			}
			sb.append("\n");
			bw.write(sb.toString());
		}
		bw.flush();
		bw.close();
	}
}

